package com.itheima.service;

import com.itheima.service.big.UserServiceImplSon;
import com.itheima.service.big.UserServiceProxy;
import com.itheima.service.impl.UserServiceImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class TestUser {

    public static void main(String[] args) {

//        UserServiceImpl userService = new UserServiceImpl();
//        UserServiceProxy userServiceProxy = new UserServiceProxy(userService);
//
//        userServiceProxy.find();


//        UserServiceImplSon userServiceImplSon=new UserServiceImplSon();
//        userServiceImplSon.find();


        //动态代理

        //创建代理类对象
        UserServiceImpl userService=new UserServiceImpl();

        //获取类加载器
        ClassLoader classLoader = userService.getClass().getClassLoader();

        //获取所有实现接口
        Class<?>[] interfaces = userService.getClass().getInterfaces();

        //创建代理类对象
        UserService proxy = (UserService) Proxy.newProxyInstance(classLoader, interfaces, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

//                System.out.println("代理类...");
                //增强方法

                System.out.println("代理类中的增强方法....");
                //执行原有方法
                Object result = method.invoke(userService, args);

                //增强方法
                System.out.println("代理类中的增强方法....");

                return result;
            }
        });

        proxy.find();

    }
}
